package com.ruoyi.framework.oauth;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.json.JSON;
import com.ruoyi.common.json.JSONObject;
import com.ruoyi.common.utils.http.HttpUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import java.util.Map;

/**
 * spring-demo-client2 发起登录请求：
 * redirect到：http://sso.maxkey.top/sign/authz/oauth/v20/authorize?client_id=830517174152986624&redirect_uri=http://localhost:8081/login&response_type=code&state=8GAmwd'
 *
 * 显示makey登录界面
 * 用户登录后
 * maxkey根据应用设置，使用自动approve，不需要用户点击授权。
 * redirect到：http://localhost:8081/login?code=72107fc4-5305-4aa5-a8d0-14da30ed0ca1&state=8GAmwd
 *
 * spring-demo-client2 的spring security自动处理，获取access_token：
 * 调用：http://sso.maxkey.top/sign/authz/oauth/v20/token
 * 参数为：
 * {
 *     grant_type=[authorization_code],
 *     code=[72107fc4-5305-4aa5-a8d0-14da30ed0ca1],
 *     redirect_uri=[http://localhost:8081/login],
 *     client_id=[830517174152986624],
 *     client_secret=[ElHEMDcwMzIwMjMxNjE5NTAyMTIx1K]
 * }
 * 得到access_token：dbff79de-6efa-4148-aedb-333325dc30c0
 *
 * spring-demo-client2的spring security使用得到access_token自动获取用户信息：
 * http://sso.maxkey.top/sign/api/oauth/v20/me
 *
 * spring-demo-client2得到用户信息后返回前端：
 * http://localhost:8081/hello
 */
@Component
public class OauthService {
    @Autowired
    private UcenterProperties ucenterProperties;
    /**
     * 根据code获取token
     * @param code
     * @return
     */
    public String getToken(String code) throws Exception {
        Assert.notNull(code,"code不能为空");
        String url = String.format("%s?client_id=%s&client_secret=%s&grant_type=authorization_code&redirect_uri=%s&code=%s",ucenterProperties.getAccessTokenUri(),ucenterProperties.getClientId(),ucenterProperties.getClientSecret(),ucenterProperties.getRedirect_uri(),code);
        String token= HttpUtils.sendGet(url);
        ObjectMapper objectMapper = new ObjectMapper();
        Map<String, String> map = objectMapper.readValue(token, new TypeReference<Map<String, String>>() {});
        return map.get("access_token").toString();
    }

    /**
     * {"birthday":null,"gender":1,"displayName":"系统管理员","departmentId":"105","mobile":"15618726256","createdate":"2014-01-20 16:00:00","title":"系统管理员","userId":"1","online_ticket":"OT910206456400183296","employeeNumber":"2099001","realname":"系统管理员","institution":"1","randomId":"f7d84163-f94a-456d-bc48-273984641efa","state":"北京","department":"科技部","user":"admin","email":"shimingxy@qq.com","username":"admin"}
     * @param accessToken
     * @return
     * @throws Exception
     */
    public String getUserInfo(String accessToken) throws Exception {
        String url = ucenterProperties.getUserInfoUri()+"?access_token="+accessToken;
        String userInfo = HttpUtils.sendGet(url);
        ObjectMapper objectMapper = new ObjectMapper();
        Map<String, String> map = objectMapper.readValue(userInfo, new TypeReference<Map<String, String>>() {});
        return map.get("userId").toString();
    }

    public class TokenResponse{
        public TokenResponse(){}
        private String access_token;
        private String token_type;
        private Integer expires_in;
        private String scope;

        public String getAccess_token() {
            return access_token;
        }

        public void setAccess_token(String access_token) {
            this.access_token = access_token;
        }

        public String getToken_type() {
            return token_type;
        }

        public void setToken_type(String token_type) {
            this.token_type = token_type;
        }

        public Integer getExpires_in() {
            return expires_in;
        }

        public void setExpires_in(Integer expires_in) {
            this.expires_in = expires_in;
        }

        public String getScope() {
            return scope;
        }

        public void setScope(String scope) {
            this.scope = scope;
        }
    }
    public class UserInfo{
        public UserInfo(){}
        private String userid;

        public String getUserid() {
            return userid;
        }

        public void setUserid(String userid) {
            this.userid = userid;
        }
    }
}
